package com.cloud.easyexcel.controller;

import com.alibaba.excel.EasyExcel;
import com.cloud.easyexcel.entity.CiticAmountRecord1;
import com.cloud.easyexcel.entity.CiticAmountRecordExcel;
import com.cloud.easyexcel.service.SysProductBomService;
import com.cloud.easyexcel.utils.BeanConverUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@RestController
public class ExcelController {
    @Resource
    private SysProductBomService sysProductBomService;

    /**
     * BOM模板导出
     **/
    @GetMapping("/excel/template")
    public void downloadTemplate(HttpServletResponse response) {
        sysProductBomService.downloadTemplate(response);
    }

    /**
     * BOM导入
     *
     * @return
     */
    @PostMapping("/excel/import")
    public void importTemplateData(@RequestParam("file") MultipartFile file,
                                   @RequestParam("versionId") Integer versionId) {
        sysProductBomService.importTemplateData(file, versionId);
    }

    /**
     * BOM导出
     *
     * @return
     */
    @GetMapping("/excel/export")
    public void export(HttpServletResponse response) throws Exception {
        String export = sysProductBomService.export(response);
    }

    @GetMapping("/excel/export/test")
    public void exportTest(HttpServletResponse response) throws Exception {

        List<CiticAmountRecord1> list = new ArrayList<>();
        CiticAmountRecord1 record1 = new CiticAmountRecord1();

        record1.setUserId("测试用户ID");
        record1.setMchntId("123567");

        CiticAmountRecord1 record2 = new CiticAmountRecord1();

        record2.setUserId("测试用户IDabcd");
        record2.setMchntId("12356789");

        list.add(record1);
        list.add(record2);

        // 生成文件名称
        String sheetName = "中信资金明细数据";

//        // 1. 设置响应头
        List<CiticAmountRecordExcel> citicAmountRecordExcels = BeanConverUtil.convertList(list, CiticAmountRecordExcel.class);


//        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//        response.setHeader("Content-Disposition",
//                "attachment;filename=" + URLEncoder.encode(sheetName+".xlsx", "UTF-8"));

        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(sheetName+".xlsx", "UTF-8"));
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf8");
        EasyExcel.write(response.getOutputStream(), CiticAmountRecordExcel.class)
                .sheet(sheetName)
                .doWrite(citicAmountRecordExcels);
    }
}
